<template>
  <div class="search-container">
    <div class="header">
      <div class="back" @click="$router.back()"><van-icon name="arrow-left" />返回</div>
      <div class="search">
        <van-search @blur="showHistory" @clear="onClear" v-model="keyword" show-action placeholder="请输入搜索关键词" @search="onSearch" shape="round">
          <template #action>
            <div @click="onSearch" class="search-btn">搜索</div>
          </template>
        </van-search>
      </div>
    </div>
    <div class="search-content" v-if="searchResult.length === 0 && showEmpty === false">
      <!-- 搜索历史 -->
      <div class="search-history" v-if="historySearchData.length > 0">
        <div class="title">
          <div>搜索历史</div>
          <van-icon name="delete" class="clear" @click="clearSearchHistory" />
        </div>
        <ul class="search-list">
          <li class="search-item" v-for="item in historySearchData" :key="item.id" @click.stop="searchHistory(item.name)">
            <span>{{ item.name }}</span>
            <van-icon class="close" name="close" @click.stop="delSearchHistory(item.id)" />
          </li>
        </ul>
      </div>
      <!-- 热门搜索 -->
      <div class="hot-content" v-if="hotSearchData.length > 0">
        <div class="hot-title">热搜榜</div>
        <ul class="hot-list">
          <li class="hot-item" v-for="(item, index) in hotSearchData" :key="item.id" @click="searchHistory(item.name)">
            <span>{{ index + 1 }}.&nbsp;</span>
            <span class="text">{{ item.name }}</span>
          </li>
        </ul>
      </div>
    </div>

    <!-- 搜索结果 -->
    <div class="search-result-list" v-if="searchResult.length > 0">
      <goods-item v-for="item in searchResult" :key="item.id" :goods_img="item.goods_img" :goods_name="item.goods_name" :goods_price="item.goods_price" :id="item.id"></goods-item>
    </div>
    <!-- 搜索结果为空 -->
    <div v-if="showEmpty"><van-empty image="search" description="暂无搜索结果！" /></div>
  </div>
</template>

<script>
import { Notify } from 'vant'
import axios from '@/utils/request/request.js'
import GoodsItem from '../publicComponent/GoodsItem.vue'
export default {
  name: 'search',
  data() {
    return {
      keyword: '',
      historySearchData: [], // 搜索历史
      hotSearchData: [], // 人额搜索
      searchResult: [], // 搜索结果
      showEmpty: false
    }
  },
  components: {
    GoodsItem
  },
  watch: {
    keyword: {
      handler() {
        if (!this.keyword) {
          this.getHistorySearchData()
          this.getHotSearchData()
        }
      },
      immediate: true
    }
  },
  methods: {
    // 当搜索框失去焦点之后如果关键词和搜索结果为空就显示热门搜索和搜索历史
    showHistory() {
      if (!this.keyword && this.searchResult.length === 0) {
        this.showEmpty = false
      }
    },
    // 点击搜索历史或者热门搜索进行搜索
    async searchHistory(name) {
      this.showEmpty = false
      this.keyword = name
      this.onSearch()
    },
    // 发起搜索
    async onSearch() {
      if (this.keyword === '') return Notify({ type: 'danger', message: '请输入搜索关键词！', duration: 500 })
      this.$toast.loading({
        message: '加载中...',
        duration: 0
      })
      try {
        const data = await axios.get('/user/search', {
          params: {
            keyword: this.keyword
          }
        })
        if (data.code === 0) {
          this.searchResult = data.data
          if (data.data.length === 0) {
            this.showEmpty = true
          } else {
            this.showEmpty = false
          }
        } else {
          Notify({
            type: 'danger',
            message: data.msg,
            duration: 1000
          })
        }
      } catch (err) {
        Notify({
          type: 'danger',
          message: '搜索失败！',
          duration: 1000
        })
      } finally {
        this.loading = false
        this.$toast.clear()
      }
    },
    // 清除搜索框中的内容
    onClear() {
      this.keyword = ''
    },
    // 获取搜索历史
    async getHistorySearchData() {
      try {
        const data = await axios.get('/user/history/search')
        if (data.code === 0) {
          this.historySearchData = data.data
        } else if (data.msg === '身份验证失败！' || data.code === 403) {
          localStorage.removeItem('user_token')
          Notify({
            type: 'danger',
            msg: data.msg,
            duration: 1000
          })
        } else {
          Notify({
            type: 'danger',
            message: data.msg,
            duration: 1000
          })
        }
      } catch (err) {
        Notify({
          type: 'danger',
          message: '获取搜索历史失败！',
          duration: 1000
        })
      }
    },
    // 获取热门搜索
    async getHotSearchData() {
      try {
        const data = await axios.get('/api/hot/search')
        if (data.code === 0) {
          this.hotSearchData = data.data
        } else {
          Notify({
            type: 'danger',
            message: data.msg,
            duration: 1000
          })
        }
      } catch (err) {
        Notify({
          type: 'danger',
          message: '获取热门搜索失败！',
          duration: 1000
        })
      }
    },
    // 清空搜索历史
    async clearSearchHistory() {
      this.$toast.loading({
        message: '加载中...',
        duration: 0
      })
      try {
        const data = await axios.post('/user/clear/search/history')
        if (data.code === 0) {
          // 删除成功
          this.getHistorySearchData()
        } else if (data.code === 403 || data.msg === '身份验证失败！') {
          localStorage.removeItem('user_token')
          Notify({
            type: 'danger',
            message: '身份验证失败！',
            duration: 1000,
            onClose: () => {
              this.$router.replace('/login')
            }
          })
        } else {
          Notify({
            type: 'danger',
            message: '删除失败！',
            duration: 1000
          })
        }
      } catch {
        Notify({
          type: 'danger',
          message: '服务器发生错误！',
          duration: 500
        })
      } finally {
        this.$toast.clear()
      }
    },
    // 删除一条搜索历史
    async delSearchHistory(id) {
      this.$toast.loading({
        message: '加载中...',
        duration: 0
      })
      try {
        const data = await axios.post('/user/del/search/history', {
          id
        })
        if (data.code === 0) {
          // 删除成功
          this.getHistorySearchData()
        } else if (data.code === 403 || data.msg === '身份验证失败！') {
          localStorage.removeItem('user_token')
          Notify({
            type: 'danger',
            message: '身份验证失败！',
            duration: 1000,
            onClose: () => {
              this.$router.replace('/login')
            }
          })
        } else {
          Notify({
            type: 'danger',
            message: '删除失败！',
            duration: 1000
          })
        }
      } catch {
        Notify({
          type: 'danger',
          message: '服务器发生错误！',
          duration: 1000
        })
      } finally {
        this.$toast.clear()
      }
    }
  },
  created() {
    this.keyword = this.$route.query.keyword ? this.$route.query.keyword : ''
    if (this.keyword) {
      this.onSearch()
    }
  }
}
</script>

<style lang="less" scoped>
.search-container {
  padding-top: 46px;
  min-height: 100vh;
  background-color: #f5f5f5;

  .header {
    position: fixed;
    top: 0;
    left: 0;
    height: 46px;
    border-bottom: 1px solid #f1f1f1;
    width: 100vw;
    z-index: 999;
    display: flex;
    align-items: center;
    background-color: #fff;

    .back {
      flex-shrink: 0;
      font-size: 14px;
      color: #323232;
      padding: 0 5px 0 16px;
      font-weight: 500;

      ::v-deep .van-icon {
        color: #323232;
        padding-right: 2px;
        font-weight: 500;
      }
    }

    .search {
      flex: 1;
    }

    ::v-deep .van-search {
      padding: 5px 12px;
    }

    ::v-deep .van-search__action {
      padding: 0 0 0 8px;
    }
    .search-btn {
      background-color: #ee0a24;
      border-radius: 999px;
      color: #fff;
      width: 50px;
      height: 24px;
      text-align: center;
      line-height: 24px;
    }
  }

  .search-content {
    padding: 10px;
    background-color: #fff;

    .search-history {
      .title {
        display: flex;
        justify-content: space-between;
        align-items: center;

        div {
          font-weight: 700;
          font-size: 18px;
        }

        .clear {
          font-size: 14px;
        }
      }
      .search-list {
        display: flex;
        flex-wrap: wrap;
        padding: 10px 0;

        .search-item {
          position: relative;
          font-size: 12px;
          border-radius: 999px;
          background-color: rgba(0, 0, 0, 0.1);
          color: #323232;
          padding: 3px 25px 3px 15px;
          margin: 0 15px 10px 0;

          .close {
            position: absolute;
            right: 0;
            top: 0;
          }
        }
      }
    }

    .hot-content {
      .hot-title {
        font-weight: 900;
        font-size: 18px;
        padding-bottom: 10px;
        color: transparent;
        background-image: linear-gradient(#ff9618, #f2501f, #f01226);
        background-clip: text;
      }

      .hot-list {
        .hot-item {
          font-size: 14px;
          padding: 5px 0;
          display: flex;
        }

        .text {
          white-space: nowrap;
          text-overflow: ellipsis;
          overflow: hidden;
        }

        .hot-item span:first-child {
          font-weight: 500;
          font-style: italic;
          flex-shrink: 0;
          font-size: 16px;
        }

        .hot-item:nth-of-type(1) span:first-child {
          color: #ee0a24;
          font-size: 18px;
          font-weight: 600;
        }
        .hot-item:nth-of-type(2) span:first-child {
          color: #f47149;
          font-size: 18px;
          font-weight: 600;
        }
        .hot-item:nth-of-type(3) span:first-child {
          color: #ff9618;
          font-size: 18px;
          font-weight: 600;
        }
      }
    }
  }

  .search-result-list {
    padding: 0 10px;
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
  }
}
</style>
